import lejos.nxt.*;

public class LineDetector extends Thread implements SensorPortListener {
	private LightSensor lightSensor = new LightSensor(
			Configuration.LIGHTSENSOR_PORT, true);
	private ColorLightSensor colorSensor = new ColorLightSensor(
			Configuration.COLOR_LIGHTSENSOR_PORT,
			SensorConstants.TYPE_COLORBLUE);
	private boolean isCalibrated = false;
	private MowController mc;
	private boolean lightSensorLine = false, colorSensorLine = false;

	public LineDetector(MowController mc) {
		setDaemon(true);
		Configuration.LIGHTSENSOR_PORT.addSensorPortListener(this);
		this.mc = mc;
	}

	public void stateChanged(SensorPort port, int kleurOud, int kleurNieuw) {
		if (isCalibrated == true) {
			int sensorValue = lightSensor.readValue();
			if (!lightSensorLine && (sensorValue > 70)) {
				lightSensorLine = true;
				mc.lineReached(port);
			} else if (sensorValue < 70) {
				lightSensorLine = false;
			}
		}
	}

	public void run() {
		while (true) {
			int value = colorSensor.readValue();
			if (!colorSensorLine
					&& value > Configuration.COLOR_SENSOR_WHITE_THRESHOLD) {
				colorSensorLine = true;
				mc.lineReached(Configuration.COLOR_LIGHTSENSOR_PORT);
			} else if (value < Configuration.COLOR_SENSOR_WHITE_THRESHOLD) {
				colorSensorLine = false;
			}
			try {
				Thread.sleep(Configuration.COLOR_SENSOR_INTERVAL);
			} catch (InterruptedException e) {
			}
		}
	}

	public void calibrate() {
		if (isCalibrated == false) {
			DebugLogger.write("LightSensor Kalibreren.", true);
			Button.waitForPress();
			// Wit calibreren.
			DebugLogger.write("Zet de sensoren op wit en druk op Enter...",
					true);
			Button.waitForPress();

			// Wit Setten op het sensorport.
			int valueWhite = lightSensor.readValue();
			DebugLogger.write("White = " + valueWhite);
			lightSensor.calibrateHigh();
			colorSensor.calibrateHigh();

			// Donkergroen calibreren.
			DebugLogger.write(
					"Zet de sensor op donkergroen en druk op Enter...", true);
			Button.waitForPress();

			// Donkergroen setten op het sensorport.
			int valueGreen = lightSensor.readValue();
			DebugLogger.write("Groen = " + valueGreen);
			lightSensor.calibrateLow();
			colorSensor.calibrateLow();

			isCalibrated = true;
		} else {
			System.out.println("De lightsensor is al gekalibreerd.");
		}
	}

	public boolean getIsCalibrated() {
		return isCalibrated;
	}
}